// src/features/workspaces/api/use-create-workspace.ts
import {useCallback, useMemo, useState} from "react";
import {MARK_DATA_URL} from "@/lib/social/constants";
import {v4 as uuidv4} from 'uuid';
import {useCurrentUser} from "@/hooks/use-current-user";
// import crypto from "crypto";

type Options = {
    onSuccess?: (workspaceId: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    name: string
    userId: string
} | null
type ResponseType = {
    id: string
    name: string
    userId: string,
    joinCode: string
} | null

const generateCode = () => {
    const code = Array.from(
        {length: 6},
        () => '0123456789abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 36)]
    ).join('')
    return code
}

// client
export const useCreateWorkspace = () => {
    // create db workspace

    const [data, setData] = useState<ResponseType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    // const [isPending, setIsPending] = useState<boolean>(false)
    // const [isSuccess, setIsSuccess] = useState<boolean>(false)
    // const [isSettled, setIsSettled] = useState<boolean>(false)
    // const [isError, setIsError] = useState<boolean>(false)

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        try {
            setData(null)
            setError(null)
            setStatus('pending')

            // 6位随机数+四舍五入 (用crypto会卡住, 不知道为啥)
            // const joinCode = Math.floor(Math.random() * 999_999).toString()
            const joinCode = generateCode()

            // create workspace
            // const response = await fetch(`${MARK_DATA_URL}/workspaces`, {
            const response = await fetch(`/api/workspaces`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    ...values,
                    joinCode,
                })
            })
            const data = await response.json()

            // 当前user作为该工作区的member(admin)
            // await fetch(`${MARK_DATA_URL}/members`, {
            await fetch(`/api/members`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId: values?.userId,
                    workspaceId: data.workspace.id,
                    role: 'admin',
                })
            })

            // 创建workspace的默认频道channel
            // await fetch(`${MARK_DATA_URL}/channels`, {
            await fetch(`/api/channels`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    workspaceId: data.workspace.id,
                    name: 'general',
                })
            })

            setStatus('success')
            if (response.ok) options?.onSuccess?.(data.workspace.id)
            return data.workspace.id
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            options?.onSettled?.()
            // window.location.reload()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled, data, isError
    }
}